package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.mainConsult.ConsultDetailActivity;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.entity.ExpertTypeL4VO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.MainCosultVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.LocationXML;
import com.digitalchina.lxnsy.xml.PersonalInfoXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/2 15:17
 * 修改备注：
 * ================================================
 */
public class ConsultIssueV2Activity extends BaseActivity {

    @Bind(R.id.consult_issue_et_issue)
    EditText consultIssueEtIssue;
    @Bind(R.id.consult_issue_tv_address)
    TextView consultIssueTvAddress;
    @Bind(R.id.consult_issue_layout_address)
    LinearLayout consultIssueLayoutAddress;
    @Bind(R.id.consult_issue_tv_type)
    TextView consultIssueTvType;
    @Bind(R.id.consult_issue_layout_type)
    RelativeLayout consultIssueLayoutType;
    @Bind(R.id.consult_issue_tv_range)
    TextView consultIssueTvRange;
    @Bind(R.id.consult_issue_layout_range)
    RelativeLayout consultIssueLayoutRange;
    @Bind(R.id.consult_issue_btn_ask)
    Button consultIssueBtnAsk;

    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;


    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private int maxImgCount = 4;               //允许选择图片最大数
    private List<String> filePath = new ArrayList<>(); // 图片地址

    private ExpertNewVO expertVO;
    private OptionsPickerView pvOptions; // 种类选择器
    private OptionsPickerView researchOptions; // 研究方向选择器
    private boolean optionTag = false;

    private boolean selectAddress = false;

    private List<ExpertTypeL4VO> oneList = new ArrayList<>(); // 父类
    private List<ExpertTypeL4VO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean.ResearchDirectionVosBean> researchList = new ArrayList<>(); // 三级研究方向

    private String address = "";
    private String maxTypeCode = "";
    private String minTypeCode = "";
    private String researchCode = "";
    private String typeName = "";
    private String rangeName = "";
    private String keyWord = "";

    private String orderNo = "";

    private String imgs = ""; // 图片 多张以逗号隔开
    private int imgIndex = -1;// 图片选择下标
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[4];
    private List<String> imgList = new ArrayList<>();
    private String[] imgArray = {"", "", "", ""};
    private int select = 0;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_consult_issue_v2);
        setTitle("咨询问题");
    }

    @Override
    public void initMember() {

        if (getIntent().hasExtra("single")) {
            // 单聊 则隐藏选择分类
            consultIssueLayoutType.setVisibility(View.GONE);
            consultIssueLayoutRange.setVisibility(View.GONE);
            expertVO = (ExpertNewVO) getIntent().getSerializableExtra("single");
            //如果是付费则取订单号
            if ("1".equals(expertVO.getConsultIsFee())) {
                orderNo = expertVO.getOrderNo();
            }
        } else {
            // 获取专家类型 仅包含有专家的分类
            BusinessExpert.expertTypeChat(this,"0", mHandler);
            setRightText("历史提问");
        }


        if (!StringUtil.isStrEmpty(LocationXML.getLocationAddress(this))) {
            address = LocationXML.getLocationAddress(this);
            consultIssueTvAddress.setText(address);
            selectAddress = true;
        }

        //打开选择,本次允许选择的数量
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
//        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
//        imagePicker.setFocusWidth(380);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setFocusHeight(380);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setOutPutX(400);//保存文件的宽度。单位像素
//        imagePicker.setOutPutY(400);//保存文件的高度。单位像素
//        imagePicker.setSelectLimit(maxImgCount - selectedImageList.size()); //选中数量限制

        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;
    }

    @Override
    public void addListener() {
        sdvImg0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage(0);
            }
        });
        sdvImg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage(1);
            }
        });
        sdvImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage(2);
            }
        });
        sdvImg3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage(3);
            }
        });

    }

    // 选择图片
    private void selectImage(int i) {
        select = i;
        if (StringUtil.isStrEmpty(imgArray[select])) {
            Intent intent = new Intent(activity, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(activity)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgArray[select] = "";
                            Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);
                            sdvArray[select].setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_EDIT_PERSONAL_INFO_BY_ID_SUCCESS: // 修改个人信息
                        PersonalInfoXML.setAddress(activity, address);
                        break;
                    case MSG.MSG_EDIT_PERSONAL_INFO_BY_ID_FIELD:
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_EXPERT_TYPE_CHAT_SUCCESS: // 获取咨询问题分类
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_EXPERT_TYPE_CHAT_FIELD:
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            imgArray[select] = fileVO.getName();
                            setImageView(fileVO.getName());
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_SAVE_GROUP_MSG_SUCCESS:
                        new MaterialDialog.Builder(activity)
                                .title("提示")
                                .content("快速提问成功，等待专家回复。")
                                .positiveText("确定")
                                .cancelable(false)
                                .canceledOnTouchOutside(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        GotoUtil.gotoActivity(activity, MassHistoryListActivity.class, true);
                                    }
                                })
                                .show();
                        break;
                    case MSG.MSG_SAVE_GROUP_MSG_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG_S_0:
                        //发送消息成功
                        final MainCosultVO vo = FastJsonUtil.getBean(msg.obj.toString(), "consultSessionInfo", MainCosultVO.class);
                        new MaterialDialog.Builder(activity)
                                .title("提示")
                                .content("发送成功！")
                                .positiveText("确定")
                                .cancelable(false)
                                .canceledOnTouchOutside(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                        GotoUtil.gotoActivity(activity, ConsultDetailActivity.class, true, "vo", vo);
                                    }
                                })
                                .show();
                        break;
                    case MSG_F_0:
                        //发送消息失败
                        showToast(msg.obj.toString() + "");
                        break;
                }
            }
        };
    }

    private void setImageView(String fileName) {
        FrescoUtil.showImageSmall(fileName, sdvArray[select]);
    }


    @Override
    public void callBack(Object object) {

        oneList = FastJsonUtil.getListBean(object.toString(), "typeList", ExpertTypeL4VO.class);
        List<List<ExpertTypeL4VO.ResearchFieldTwoStagesBean>> twoList = new ArrayList<>();
        List<List<List<ExpertTypeL4VO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean>>> threeList = new ArrayList<>();

        if (oneList == null || oneList.size() == 0)
            return;


        for (int i = 0; i < oneList.size(); i++) {
            twoList.add(oneList.get(i).getResearchFieldTwoStages());
        }

        for (int i = 0; i < oneList.size(); i++) {
            List<List<ExpertTypeL4VO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean>> temp2 = new ArrayList<>();
            for (int j = 0; j < oneList.get(i).getResearchFieldTwoStages().size(); j++) {
                List<ExpertTypeL4VO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean> temp1 = oneList.get(i).getResearchFieldTwoStages().get(j).getResearchFieldThreeStageVos();
                temp2.add(temp1);
            }
            threeList.add(temp2);
        }


        // 条件选择器初始化
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String opt1 = oneList.get(options1).getPickerViewText();
                String opt2 = oneList.get(options1).getResearchFieldTwoStages().get(option2).getPickerViewText();
                String opt3 = oneList.get(options1).getResearchFieldTwoStages().get(option2).getResearchFieldThreeStageVos().get(options3).getPickerViewText();

                consultIssueTvType.setText(opt1 + "  " + opt2 + "  " + opt3);
                maxTypeCode = oneList.get(options1).getCode();
                minTypeCode = oneList.get(options1).getResearchFieldTwoStages().get(option2).getResearchFieldThreeStageVos().get(options3).getCode();
                typeName = opt1 + "-" + opt2 + "-" + opt3;

                consultIssueTvRange.setText("");
                researchList.clear();
                researchList.addAll(oneList.get(options1).getResearchFieldTwoStages().get(option2).getResearchFieldThreeStageVos().get(options3).getResearchDirectionVos());
            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("作物种类")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 0)  //设置默认选中项
                .build();

        pvOptions.setPicker(oneList, twoList, threeList);


        researchOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                researchCode = researchList.get(options1).getCode();
                consultIssueTvRange.setText(researchList.get(options1).getName());

            }
        })
                .setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("咨询范围")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 0)  //设置默认选中项
                .build();

    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoActivity(activity, MassHistoryListActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        optionTag = false; // 默认将tag置为false  避免自动弹出选择器
    }

    @OnClick({R.id.consult_issue_layout_address, R.id.consult_issue_layout_type, R.id.consult_issue_layout_range, R.id.consult_issue_btn_ask})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.consult_issue_btn_ask: // 提问按钮

                String issue = consultIssueEtIssue.getText().toString();
                if (!selectAddress) {
                    showToast("请选择所在区域！");
                    return;
                }
                if (!getIntent().hasExtra("single")) {
                    if (StringUtil.isStrEmpty(consultIssueTvType.getText().toString())) {
                        showToast("请选择作物种类！");
                        return;
                    }
//                    if (StringUtil.isStrEmpty(consultIssueTvRange.getText().toString())) {
//                        showToast("请选择咨询范围！");
//                        return;
//                    }


                }
                if (StringUtil.isStrEmpty(issue)) {
                    showToast("请输入描述问题!");
                    return;
                }

                imgs = "";
                for (String s : imgArray) {
                    if (!StringUtil.isStrEmpty(s))
                        imgs += s + ",";
                }

//                LogUtils.e(imgs);
                if (getIntent().hasExtra("single")) {
                    sendMsg(issue);
                } else {
                    sendMulti();
                }


                break;
            case R.id.consult_issue_layout_address:
                showAddressPicker();
                break;
            case R.id.consult_issue_layout_type:
                if (pvOptions != null) {
                    pvOptions.show();
                } else {
                    showToast("正在获取作物种类");
                    optionTag = true;
                    BusinessExpert.expertTypeChat(activity,"0", mHandler);
                }
                break;
            case R.id.consult_issue_layout_range:
                if (StringUtil.isStrEmpty(consultIssueTvType.getText().toString())) {
                    showToast("请选择作物种类作物种类");
                    return;
                }

                researchOptions.setPicker(researchList);
                researchOptions.show();
                break;
        }
    }

    private String content = "";

    private void sendMulti() {
        content = "您好，我是来自" + address + "的用户，我遇到的问题是：" + consultIssueEtIssue.getText().toString();
        BusinessExpert.saveGroupMsg(this, minTypeCode, researchCode, content, imgs, mHandler);
        BusinessAccount.saveUserBehaviorByMobile(this, Constant.BEHAVIOR_EXPERT_CONSULT_GROUP, minTypeCode, mHandler);
    }

    /**
     * 单聊
     *
     * @param issue
     */
    private void sendMsg(String issue) {

        if (StringUtil.isStrEmpty(address) && StringUtil.isStrEmpty(typeName)) { // 只发问题
            keyWord = String.format("您好，我遇到的问题是：%s", issue);
        } else if (!StringUtil.isStrEmpty(address) && StringUtil.isStrEmpty(typeName)) { // 只发问题和地址
            keyWord = String.format("您好，我是来自%s的用户，我遇到的问题是：%s", address, issue);
        } else if (!StringUtil.isStrEmpty(address) && !StringUtil.isStrEmpty(typeName)) { // 问题 地址 作物分类
            keyWord = String.format("您好，我是来自%s的用户，作物分类为%s，我遇到的问题是：%s", address, typeName, issue);
        } else { // 所需个人信息完整
            keyWord = String.format("您好，我是来自%s的用户，作物分类为%s，我遇到的问题是：%s", address, typeName, issue);
        }


        HttpParams params = new HttpParams();
        params.put("userAccId", UserXML.getUserId(activity));
        params.put("orderNo", orderNo);
        params.put("content", keyWord);
        params.put("imgId", imgs);
        params.put("expertId", expertVO.getId());

        OkHttpUtil.post(activity, URL.URL_CONSULT_QUESTION, "正在发送...", params, mHandler,
                MSG_S_0, MSG_F_0);


        BusinessAccount.saveUserBehaviorByMobile(this, Constant.BEHAVIOR_EXPERT_CONSULT_SINGLE, expertVO.getId(), mHandler);

    }

    /**
     * 所在区域选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(activity);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                String provinceCode = province.province_code;
                String cityCode = city != null ? city.city_code : "";
//                String countyCode = county != null ? county.county_code : "";
//                String code[] = new String[3];
//                code[0] = provinceCode;
//                code[1] = cityCode;
//                code[2] = countyCode;
                if (provinceCode.equals("110000") || provinceCode.equals("120000") || provinceCode.equals("310000") || provinceCode.equals("500000") || (provinceCode.equals("460000") && cityCode.equals("469000"))) {
                    address = String.format("%s %s", province.province_name, county != null ? county.county_name : "");
                    consultIssueTvAddress.setText(address);
                } else {
                    address = String.format("%s %s %s", province.province_name,
                            city != null ? city.city_name : "", county != null ? county.county_name : "");
                    consultIssueTvAddress.setText(address);
                }

//                if (StringUtil.isStrEmpty(PersonalInfoXML.getAddress(ConsultIssueV2Activity.this)))
//                    BusinessAccount.editPersonalBaseInfo(ConsultIssueV2Activity.this, editAddress(code), mHandler);
                selectAddress = true;
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }


}
